package com.xxtx.trade.config;

import com.alibaba.fastjson.JSONObject;
import com.xxtx.trade.common.util.StringUtil;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.jwt.BaseContextHandler;
import com.xxtx.trade.jwt.IJWTInfo;
import com.xxtx.trade.jwt.JwtTokenExtUtil;
import com.xxtx.trade.sysUser.enums.TradeSysUserEnum;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * 用于查询该token对应的用户是否存在
 *
 * @Author: Jay.Wang
 * @Description:
 */
public class UserInterceptor implements HandlerInterceptor {


    @Autowired
    private CacheManager cacheManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果是微信开头，直接跳过
        String url = request.getRequestURI();
        if(request.getRequestURI().contains("/api/v1/xxtx/wx/")){
            String appid = request.getHeader("appid");
            if(!StringUtil.isEmpty(appid)) {
                BaseContextHandler.setAppId(appid);
                //获取ICCID
                BaseContextHandler.setUserID(appid);
                return true;
            }else{
                writeTokenIllegal(response,40505); //token过期
                return false;
            }
        }
        // 这些链接无需token验证，直接放行
        if(url.startsWith("/api/v1/xxtx/wx")){
            return true;
        }
        if(url.startsWith("/api/v1/xxtx/tiktok/get/dianji/zj")){
            return true;
        }
        if(url.startsWith("/api/v1/xxtx/tencent/get/dianji/zj")){
            return true;
        }
        if(url.startsWith("/api/v1/xxtx/baidu/get/dianji/zj")){
            return true;
        }
        if(url.startsWith("/api/v1/xxtx/kuaishou/get/dianji/zj")){
            return true;
        }
//        if (url.startsWith("/api/v1/xxtx/fieldManage/setPhoneOwnership")){
//            // 暂时开放，用来上传手机区号和归属地
//            return true;
//        }
//        if (url.startsWith("/api/v1/xxtx/fieldManage/phoneOwnershipToRedis")){
//            return true;
//        }
        if(url.contains("/api/v1/xxtx/download")){
            return true;
        }
        String token = request.getHeader("token");
        String token2 = request.getParameter("token");
        if (StringUtils.isEmpty(token) && StringUtils.isEmpty(token2)) {
            writeTokenIllegal(response, 40499);
            return true;
        }

        if ("null".equals(token) || "null".equals(token2)) {
            writeTokenIllegal(response, 40499);
            return true;
        }

        String result  = StringUtils.isEmpty(token) ? token2 : token;

        String  userId=null;
        try {
            IJWTInfo info = JwtTokenExtUtil.getInfoFromToken(result);
            if (info.isExpire()) { //token过期
                writeTokenIllegal(response, 40500); //token过期
                return true;
            }
            userId=info.getUserId();
        }catch (Exception e){
            e.printStackTrace();
            writeTokenIllegal(response, 40500); //token过期
            return true;
        }

        if(cacheManager== null){
            cacheManager = SpringUtil.getBean(CacheManager.class);
        }
        TradeSysUserVo tradeSysUserVo = (TradeSysUserVo) cacheManager.get(TradeSysUserEnum.ACCOUNT_STATE_NORMAL.getCode() + userId);
        if (tradeSysUserVo == null) {
            writeTokenIllegal(response, 40500); //token过期
            return true;
        } else {
            BaseContextHandler.setName(tradeSysUserVo.getNickName());
            BaseContextHandler.setUserID(tradeSysUserVo.getId());
            BaseContextHandler.setToken(token);
        }

        return true;
    }


    /**
     * 返回错误信息
     *
     * @param response
     * @return
     */
    private boolean writeTokenIllegal(HttpServletResponse response, Integer code) {
        response.setHeader("Content-type", "application/json;charset=UTF-8");

        try {
            OutputStream writer = response.getOutputStream();
            if (code.equals(40499)) {
                writer.write(JSONObject.toJSONString(new Result<>(40499, "token为空!", null)).getBytes("utf-8"));
            } else if (code.equals(40500)) {
                writer.write(JSONObject.toJSONString(new Result<>(40500, "token过期!", null)).getBytes("utf-8"));
            } else if (code.equals(40501)) {
                writer.write(JSONObject.toJSONString(new Result<>(40501, "登录校验失败!", null)).getBytes("utf-8"));
            } else if (code.equals(40502)) {
                writer.write(JSONObject.toJSONString(new Result<>(40502, "用户已禁用!", null)).getBytes("utf-8"));
            } else if (code.equals(40503)) {
                writer.write(JSONObject.toJSONString(new Result<>(40502, "帐号多处登录!", null)).getBytes("utf-8"));
            }
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException("系统错误", e);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
